package cn.toma.common.enumtype.handler;

import cn.toma.common.vo.StringPool;
import com.alibaba.fastjson.JSON;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: zqx
 * @Date: 2019-08-02 10:32
 * @Description: 自定义 , 逗号分隔符 数组输出 类型转换器 使用方法 给指定的属性字段
 * @ColumnType(typeHandler = JsonArrayTypeHandler.class) 指定类型转换器
 */
public class JsonArrayTypeHandler extends BaseTypeHandler<List>
{
	private static final String DELIMITER = StringPool.COMMA;

	@Override
	public void setNonNullParameter(PreparedStatement preparedStatement, int i, List params, JdbcType jdbcType) throws SQLException
	{
		preparedStatement.setString(i, JSON.toJSONString(params));
	}


	@Override
	public List getNullableResult(ResultSet resultSet, String s) throws SQLException
	{
		String str = resultSet.getString(s);
		if (resultSet.wasNull()) {
			return null;
		}
		return JSON.parseArray(str, String.class);
	}

	@Override
	public List getNullableResult(ResultSet resultSet, int i) throws SQLException
	{
		String str = resultSet.getString(i);
		if (resultSet.wasNull()) {
			return null;
		}
		return JSON.parseArray(str, String.class);
	}

	@Override
	public List getNullableResult(CallableStatement callableStatement, int i) throws SQLException
	{
		String str = callableStatement.getString(i);
		if (callableStatement.wasNull()) {
			return null;
		}
		return JSON.parseArray(str, String.class);
	}
}
